package com.zzx.boot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzx.boot.common.CustomException;
import com.zzx.boot.common.R;
import com.zzx.boot.dto.DishDto;
import com.zzx.boot.mapper.DishMapper;
import com.zzx.boot.pojo.Category;
import com.zzx.boot.pojo.Dish;
import com.zzx.boot.pojo.DishFlavor;
import com.zzx.boot.service.CategoryService;
import com.zzx.boot.service.DishFlavorService;
import com.zzx.boot.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Controller
@ResponseBody
@Slf4j
@RequestMapping("/dish")
public class DishController {

    @Resource
    private DishService service;
    @Resource
    private DishFlavorService dishFlavorService;
    @Resource
    private RedisTemplate redisTemplate;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishdto){
        String key = "dish_"+dishdto.getCategoryId()+"_1";
//        boolean save = service.save( dishdto);
//        批量添加
        R<String> save = service.saveWithFlavor(dishdto);

        redisTemplate.delete(key);

        return save;
    }


    @GetMapping("/page")
    public R<Page<DishDto>> page(Integer page,Integer pageSize,String name){
        Page<DishDto> dishPage = service.selectPage(page, pageSize, name);
        return R.success(dishPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> query(@PathVariable Long id){
        DishDto dishDto =new DishDto();
        Dish byId = service.getById(id);
        //对象拷贝
        BeanUtils.copyProperties(byId,dishDto);
        if (byId!=null){
            LambdaQueryWrapper<DishFlavor> queryWrapper  = new LambdaQueryWrapper();
            queryWrapper.eq(DishFlavor::getDishId,byId.getId());
            List<DishFlavor> list = dishFlavorService.list(queryWrapper);
            dishDto.setFlavors(list);
            return R.success(dishDto);
        }
        throw new CustomException("查询失败!");
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        R<String> update = service.update(dishDto);
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return update;
    }

    @PostMapping("/status/{status}")
    public R<String> status(String ids,@PathVariable Integer status){
        String[] split = ids.split(",");
        List<Dish> strings = new ArrayList<>();
        for (String s : split) {
            Dish dish = new Dish();
            dish.setId(Long.valueOf(s));
            dish.setStatus(status);
            strings.add(dish);
        }

        boolean update = service.updateBatchById(strings);

        Set keys = redisTemplate.keys("*");
        redisTemplate.delete(keys);

        return update?R.success("修改成功"):R.error("修改失败");
    }

    @DeleteMapping
    public R<String> delete(String ids){
        String[] split = ids.split(",");
        List<String> strings = Arrays.asList(split);
        boolean b = service.removeByIds(strings);
        Set keys = redisTemplate.keys("*");
        redisTemplate.delete(keys);
        return b?R.success("删除成功"):R.error("删除失败");
    }

/*    @GetMapping("/list")
    public R<List<Dish>> list(Long categoryId){
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Dish::getCategoryId,categoryId);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort);
        List list = service.list(queryWrapper);
        if (list==null){
            throw new CustomException("查询菜品失败!");
        }
        return R.success(list);
    }*/
@GetMapping("/list")
public R<List<DishDto>> list(Long categoryId,Integer status){
    List<DishDto> list1 = null;
    //构造key
    String key = "dish_"+categoryId+"_"+status;
    //从redis中获取key,如果存在就返回 不存在则查询数据库存储到缓存中
    //为什么可以转 因为Json就是字符串
    list1 = (List<DishDto>) redisTemplate.opsForValue().get(key);

    //如果存在则直接返回
    if (list1!=null){
        return R.success(list1);
    }
//如果不存在
    LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
    queryWrapper.eq(Dish::getCategoryId,categoryId);
    queryWrapper.orderByDesc(Dish::getUpdateTime);
    queryWrapper.eq(Dish::getStatus,status);
    queryWrapper.orderByAsc(Dish::getSort);
    List<Dish> list = service.list(queryWrapper);
    if (list==null){
        throw new CustomException("查询菜品失败!");
    }

     list1 = new ArrayList<>();

    for (Dish o : list) {
        DishDto dishDto = new DishDto();
        //查询口味
        LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper();
        BeanUtils.copyProperties(o,dishDto);
         queryWrapper1.eq(DishFlavor::getDishId, o.getId());
        List<DishFlavor> list2 = dishFlavorService.list(queryWrapper1);
        dishDto.setFlavors(list2);
        list1.add(dishDto);
    }
//查询到数据了,就存储到redis缓存中
    redisTemplate.opsForValue().set(key,list1,60, TimeUnit.MINUTES);
    return R.success(list1);
}
}
